package puyu.manage.service.security.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import puyu.manage.service.SysUser.service.SysUserServiceI;
import puyu.manage.service.security.LoginUser;
import puyu.manage.service.utils.MessageUtils;
import puyu.manage.service.utils.StringUtils;
import puyu.manage.service.utils.enums.UserStatus;
import puyu.manage.service.utils.except.BaseException;

import java.util.Map;

/**
 * 用户验证处理
 *
 * @author cxnet
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired(required = false)
    private SysUserServiceI userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        Map<String,Object> user = userService.selectUserInfoByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException(MessageUtils.message("A0100",username));
        }
        else if ("1".equals(user.get("is_del")))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException(MessageUtils.message("A0111",username));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.get("status")))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException(MessageUtils.message("A0112",username));
        }
        else if (UserStatus.LOCK.getCode().equals(user.get("status")))
        {
            log.info("登录用户：{} 已被锁定.", username);
            throw new BaseException(MessageUtils.message("A0114",username));
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(Map<String,Object> user)
    {
        return new LoginUser(user);
    }
}
